package com.controller;

import com.entity.Job;
import com.entity.Notice;
import com.util.DataSourceUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;

@WebServlet("/filter/updateJob")
public class UpdateJobServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.getRequestDispatcher("/WEB-INF/jsp/xianshi.jsp").forward(req,resp);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String jid=req.getParameter("jid");
        Job job=new Job();
        String sql="select * from Job2 where jid=?";
        try (Connection con = DataSourceUtils.getConnection();
             PreparedStatement ps=con.prepareStatement(sql)){
            ps.setString(1,req.getParameter("jid"));
            try(ResultSet rs=ps.executeQuery())
            {
                rs.next();
                job.setJid(rs.getString("jid"));
                job.setTitle(rs.getString("Title"));
                job.setDateTime(rs.getObject("PublishDate", LocalDateTime.class));
                job.setContent(rs.getString("Content"));
                job.setImageurl(rs.getString("ImageURL"));
            }
        }
        catch (SQLException e)
        {
            throw new RuntimeException(e);
        }
        String newtitle=req.getParameter("newtitle");
        String newcontent=req.getParameter("newcontent");
        String dateTimeStr = req.getParameter("newdateTime");
        LocalDateTime newdateTime= null;
        String newimageurl = req.getParameter("newimageurl");
        if (dateTimeStr!= null&& !dateTimeStr.trim().isEmpty()) {
            newdateTime=LocalDateTime.parse(dateTimeStr);
        }
        String sql2="update Job2 set Title = ?,PublishDate=?,Content=?,ImageURL=? where jid = ?";
        try (Connection con= DataSourceUtils.getConnection(); PreparedStatement ps = con.prepareStatement(sql2) ){
            ps.setString(1, (newtitle != "") ? newtitle : job.getTitle());
            ps.setObject(2, newdateTime != null ? newdateTime : job.getDateTime());
            ps.setString(3, (newcontent != "") ? newcontent : job.getContent());
            ps.setString(4, (newimageurl != "") ? newimageurl : job.getImageurl());
            ps.setString(5, jid);
            ps.executeUpdate();
        }catch (SQLException e) {
            throw new RuntimeException(e);
        }
        resp.sendRedirect(req.getContextPath()+"/filter/houtai");
    }
}
